package cn.kgc.itrip.trade.service.impl;

import cn.kgc.itrip.beans.pojo.ItripHotelOrder;
import cn.kgc.itrip.dao.itriphotelorder.ItripHotelOrderMapper;
import cn.kgc.itrip.trade.service.HotelOrderService;
import cn.kgc.itrip.utils.EmptyUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service
public class HotelOrderServiceImpl implements HotelOrderService {
    @Resource
    private ItripHotelOrderMapper itripHotelOrderMapper;

    @Override
    public void updateOrder(Map<String, String> notifyMap) throws Exception {
        String orderNo = notifyMap.get("out_trade_no");
        ItripHotelOrder itripHotelOrder = getOrderByOrderNo(orderNo);
        itripHotelOrder.setPayType(2);
        String tradeNo = notifyMap.get("transaction_id");
		 // 交易编号
        itripHotelOrder.setTradeNo(tradeNo);
		 // 支付成功
        itripHotelOrder.setOrderStatus(2);
        itripHotelOrder.setModifyDate(new Date());
        itripHotelOrderMapper.updateItripHotelOrder(itripHotelOrder);
    }

    @Override
    public boolean checkOrderStatus(Map<String, String> notifyMap) throws Exception {
        // 验证金额  因为测试金额1分钱问题 无法实现
        String orderNo = notifyMap.get("out_trade_no");
        ItripHotelOrder itripHotelOrder = getOrderByOrderNo(orderNo);
        if(EmptyUtils.isNotEmpty(itripHotelOrder)){
            if(itripHotelOrder.getOrderStatus() == 0
                    && EmptyUtils.isEmpty(itripHotelOrder.getTradeNo())){
                return true;
            }
        }
        return false;
    }

    @Override
    public void updateOrder(ItripHotelOrder itripHotelOrder) throws Exception {
        itripHotelOrderMapper.updateItripHotelOrder(itripHotelOrder);
    }

    @Override
    public ItripHotelOrder getOrderByOrderNo(String orderNo) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("orderNo",orderNo);
        List<ItripHotelOrder> itripHotelOrders = itripHotelOrderMapper.getItripHotelOrderListByMap(params);
        return EmptyUtils.isNotEmpty(itripHotelOrders) ? itripHotelOrders.get(0) : null;
    }
}
